<template>
	<div id="resourceUpload" v-loading="loading" element-loading-text="文件上传中，请勿操作">
		<div class="i_maxW">
			<div class="u_crumbs">
				<router-link to="/personal/index">个人中心</router-link>
				<strong>
					<router-link to="/personal/resource/index" class="fade-router"><i>></i>我的资源</router-link>
				</strong>
				<strong><i>></i>资源上传</strong>
			</div>
			<!--  -->
			<div class="u_resource">
				<el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="100px" class="demo-ruleForm" maxlength="20">
					<el-form-item label="上传资源" class="up_true" prop="file">
						<div class="r_fileBox resources_file">
		
							<uploader :options="uploadOptions" :class="{ Upactive: isActive }" :autoStart="false" ref="uploader" :file-status-text="statusText" @files-submitted="fileSubmit" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail" class="uploader-example">
								<uploader-unsupport></uploader-unsupport>
								<uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">
									选择文件
								</uploader-btn>
								<uploader-list></uploader-list>
							</uploader>
						</div>
						<el-input v-model="dataForm.file" class="resources_upfile" v-show="0"></el-input>
					</el-form-item>
					<el-form-item label="资源名称" prop="name">
						<el-input v-model.trim="dataForm.name" maxlength="50" placeholder="最多可输入50个字"></el-input>
					</el-form-item>

					<el-form-item label="分类" prop="cate_id" v-if='$store.state.isCheckLevel' class='  '>
						<el-select filterable v-model="dataForm.cate_id"  placeholder="请选择">
							<el-option v-for="item in classificationList" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>

					</el-form-item>

					<div class="r_typeClass">
						<!-- 学段 -->
						<el-form-item label="学段" prop="study_section_id">
							<el-select filterable v-model="dataForm.study_section_id" @change="relateChange($event,'study_section')" placeholder="请选择学段">
								<template v-for="(item ,inx) of orgLevel2">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
						<!--年级  -->
						<el-form-item label="年级" prop="grade_id">
							<el-select filterable v-model="dataForm.grade_id" @change="relateChange($event,'grade')" placeholder="请选择年级">
								<template v-for="(item ,inx) of orgLevel3">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
						<!--  -->
						<el-form-item label="科目" prop="subject_id">
							<el-select filterable v-model="dataForm.subject_id" @change="relateChange($event,'subject')" placeholder="请选择科目">
								<template v-for="(item ,inx) of orgSubject">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
						<!--  -->
						<el-form-item label="版本" prop="version_id">
							<el-select filterable v-model="dataForm.version_id" @change="relateChange($event,'version')" placeholder="请选择版本">
								<template v-for="(item ,inx) of orgVersion">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
						<!--  -->
						<el-form-item label="教材" prop="material_id">
							<el-select filterable v-model="dataForm.material_id" @change="relateChange($event,'material')" placeholder="请选择教材">
								<template v-for="(item ,inx) of orgMaterial">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
						<!--  -->
						<el-form-item label="章" prop="list_1_id">
							<el-select filterable v-model="dataForm.list_1_id" @change="relateChange($event,'list_1')" placeholder="请选择">
								<template v-for="(item ,inx) of orgList1">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
						<!--  -->
						<el-form-item label="节" prop="list_2_id">
							<el-select filterable v-model="dataForm.list_2_id" placeholder="请选择">
								<template v-for="(item ,inx) of orgList2">
									<el-option :label="item.name" :value="item.id" :key="inx"></el-option>
								</template>
							</el-select>
						</el-form-item>
					</div>
					<el-form-item label="简介" prop="profile">
						<el-input type="textarea" :rows="6" resize="none" placeholder="不超200字" show-word-limit v-model.trim="dataForm.profile" maxlength="200"></el-input>
					</el-form-item>
					<el-form-item label="权限" prop="authority">
						<el-radio-group v-model="dataForm.authority">
							<el-radio :label="1">公开</el-radio>
							<el-radio :label="0">不公开</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="允许下载" prop="is_download">
						<el-radio-group v-model="dataForm.is_download">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item class="buttonCSS" label-width="0">
						<el-button type="primary" plain @click="resetForm('dataForm')">取消</el-button>
						<el-button type="primary" @click="submitForm('dataForm')" v-preventReClick>保存</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</div>
</template>
<script>
export default {
	data() {

		return {
			orgLevelParam: { //获取学段,年纪参数
				level: 2,
				pid: 1,
				direction: 'balance',
				app_code: this.$store.getters.userInfo.app_code
			},
			orgLevel2: this.$g.orgLevel2,
			/*学段*/
			orgLevel3: {},
			/*年级*/
			orgSubject: {},
			/*科目*/
			orgVersion: {},
			/*版本*/
			orgMaterial: {},
			/*教材*/
			orgList1: {},
			/*章*/
			orgList2: {},
			/*节*/
			subjectParam: { //获取科目,版本，参数
				type: 2,
				org_id: 4,
				status: 1,
			},
			versionParam: { //获取科目,版本，参数
				type: 2,
				org_id: 0,
				sub_id: 0,
				status: 1
			},
			materialParam: { //获取科目,版本，参数
				org_id: 0,
				sub_id: 0,
				ver_id: 0,
				status: 1
			},
			listParam1: { /*章*/
				pid: 0,
				material_id: 0,
				level: 1,
			},
			listParam2: { /*节*/
				pid: 0,
				material_id: 0,
				level: 2,

			},
			selectFileShow: true, //是否显示选择文件按钮
			uploadOptions: {
				target: this.BASE_URL + '/api/resource/res_upload',
				testChunks: false,
				headers: { Authorization: `Bearer ` + this.$g.access_token },
			},
			selectFileOrNot: false, //是否选中文件
			uploadOrNot: false, //是否已经上传
			attrs: {
				//accept: ['image/*','video/*','audio/*','document/doc', 'document/txt', 'document/docx','document/csv', 'document/xls','document/xlsx', 'document/ppt', 'document/pptx']
			},
			statusText: {
				success: '上传成功',
				error: '上传出错',
				uploading: '正在上传...',
				paused: '暂停',
				waiting: '等待上传'
			},
			uploadInfo: {
				file_name: '',
				file_path: '',
				file_size: 0
			},
			dataForm: {
				name: undefined, //资源名称
				study_section_id: undefined, //学段
				grade_id: undefined, //年级
				subject_id: undefined, //科目
				version_id: undefined, //版本
				material_id: undefined, //教材
				list_1_id: undefined, // 章id
				list_2_id: undefined, // 节id
				authority: 1, //权限
				is_download: 1, //允许下载
				profile: '',
				format_pdf: 0,
				file: undefined,
				status: 2,
				cate_id: undefined
			},
			rules: {
				file: [
					{ required: true, message: '请选择上传的文件', trigger: 'change' }
				],
				name: [
					{ required: true, message: '请输入资源名称', trigger: 'change' },
					// { min: 1, max: 20, message: '长度在 0 到 20 个字符' }
				],
				study_section_id: [
					{ required: true, message: '请选择学段', trigger: 'change' }
				],
				grade_id: [
					{ required: true, message: '请选择年级', trigger: 'change' }
				],
				subject_id: [
					{ required: true, message: '请选择科目', trigger: 'change' }
				],
				profile: [
					{ required: false, message: '请输入资源名称', trigger: 'blur' }
				],
				cate_id: [{ required: true, message: '请选择分类', trigger: 'change' }]

			},
			uploadRetryTimes: 100, //文件最大重传次数
			isActive: false,
			uploadLimitMax: 2000,
			loading: false,
			classificationList: [],

		};
	},
	created() {
		let timer = setTimeout(()=>{this.orgLevel2 = this.$g.orgLevel2; clearTimeout(timer);}, 1000);
		this.$store.state.isCheckLevel &&  this.getClassification()
	},
	mounted(){

	},
	methods: {
		getClassification(){

			let success =(res)=>{
				this.classificationList = res.data
				this.classificationList.unshift({name: '全部', id: 0})
			}

			let params = {}
			this.$ajax.get('api/resource/resource_cate', { params, func: { success: success} })
		},
		/**
		 * 验证提交数据
		 * @DateTime 2020-03-05T10:41:29+0800
		 * @param    {[type]}                 formName [description]
		 * @return   {[type]}                          [description]
		 */
		submitForm(formName) {

			this.$refs[formName].validate((valid) => {
				if (valid) {


					this.loading = true
					/*文件上传*/
					if (this.selectFileOrNot) {
						this.isActive = true
						this.fileUpload();

					} else {
						this.resourceSave();
					}
				} else {
					return false;
				}
			});
		},
		/**
		 * 数据提交
		 * @DateTime 2020-03-05T10:42:51+0800
		 * @return   {[type]}                 [description]
		 */
		resourceSave() {

			let resourceParam = deep_clone(this.dataForm);
			if (this.uploadOrNot) {

				let Size = parseInt(this.uploadInfo.file_size);
				resourceParam.path = this.uploadInfo.file_path;
				resourceParam.filesize = Size;
				resourceParam.postfix = this.uploadInfo.post_fix;

			}
			let success = (data => {
				this.isActive = false
				this.loading = false
				if (this.roleBaseid(4) && this.dataForm.authority == 1) {
					this.$message.success('上传成功，请等待管理员审核')
				} else {
					this.$message.success('上传成功')
				}
				setTimeout(() => {
					this.$router.push({ path: '/personal/resource/index' })
				}, 800);

			})


			/*根据角色判断上传的资源是否要审核 1.正常 2.审核中*/
			resourceParam.status = this.roleBaseid(4, 5) ? 2 : 1
			//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
			if (!is_empty(resourceParam.id) && parseInt(resourceParam.id) > 0) {
				this.$ajax.put('api/resource/vue_resource', resourceParam, { func: { success: success } })
			} else {
				this.$ajax.post('api/resource/vue_resource', resourceParam, { func: { success: success } })
			}
		},
		resetForm(formName) {
			this.$router.back(-1)
		},
		//上传成功的事件  
		fileSuccess(rootFile, file, message, chunk) {
			var mess = JSON.parse(message);
			mess = handleResponseData(mess)
			if (parseInt(mess.data.status) === 1) {
				this.uploadOrNot = true;
				this.uploadInfo.file_name = mess.data.file_name;
				this.uploadInfo.file_path = mess.data.file_path;
				this.uploadInfo.post_fix = mess.data.post_fix;
				this.resourceSave();

			} else if (mess.status === 'fail') {
				this.$message.error(mess.msg + ' ' + file.name)
				this.$refs.uploader.uploader.cancel()
			}
		},
		fileFail(rootFile, file, message, chunk) {
			var mess = eval('(' + message + ')');
			if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
				let callbcak = (data => {
					this.uploadRetryTimes--;
					Uploader.retry(file);
				})
				this.get_access_token(callbcak);
			}
		},
		fileSubmit(files, fileList, event) {

			let name = files[0].name.replace(/\.\w+$/, '')
			if (files[0].size === 0) {
				this.$refs.uploader.uploader.cancel();
				this.$message.error('上传文件大小不能小于0')
				this.selectFileShow = true;
			} else if (files[0].size > this.uploadLimitMax * 1024 * 1024 && this.uploadLimitMax > 0) {
				this.$message.warning('只允许上传' + this.uploadLimitMax + 'M以内的文件');
				this.$refs.uploader.uploader.cancel();
			} else if (name.length > 50) {
				this.$message.error('文件名称过长，50个字以内')
				this.$refs.uploader.uploader.cancel();

			} else {
				this.uploadInfo.file_size = files[0].size;
				this.selectFileOrNot = true;
				this.selectFileShow = false;
				this.dataForm.file = this.uploadInfo.file_size
				this.dataForm.name = files[0].name.replace(/\.\w+$/, '');
			}

		},
		fileRemoved(file) {
			this.selectFileOrNot = false;
			this.selectFileShow = true;
			this.isActive = false
			this.dataForm.file = ''
			this.dataForm.name = ''
		},
		fileUpload() {

			Uploader.resume();
		},
		//获取学段
		getOrgLevel2() {

			let success = (data => {
				this.orgLevel2 = data.data;
			})

			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/newlevel/platform_org', { params: this.orgLevelParam, func: { success: success } })
			} else {
				this.$ajax.get('api/org/org', { params: this.orgLevelParam, func: { success: success } })
			}

		},
		//获取年级
		getOrgLevel3() {


			let success = (data => {
				this.orgLevel3 = data.data;
			})

			this.orgLevelParam.level = 3;
			this.orgLevelParam.pid = this.dataForm.study_section_id;

			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/newlevel/platform_org', { params: this.orgLevelParam, func: { success: success } })
			} else {
				this.$ajax.get('api/org/org', { params: this.orgLevelParam, func: { success: success } })
			}

		},
		//获取科目
		getSubject() {
			this.subjectParam.org_id = this.dataForm.grade_id;
			let success = (data => {
				this.orgSubject = data.data;
			})

			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/newlevel/platform_subject', { params: this.subjectParam, func: { success: success } })
			} else {
				this.$ajax.get('api/cate/subject', { params: this.subjectParam, func: { success: success } })
			}

		},
		//获取版本
		getVersion() {
			this.versionParam.org_id = this.dataForm.grade_id;
			this.versionParam.sub_id = this.dataForm.subject_id;

			let success = (data => {
				this.orgVersion = data.data;
			})
			this.$ajax.get('api/cate/version', { params: this.versionParam, func: { success: success } })

		},
		//获取教材
		getMaterial() {
			this.materialParam.org_id = this.dataForm.grade_id;
			this.materialParam.sub_id = this.dataForm.subject_id;
			this.materialParam.ver_id = this.dataForm.version_id;

			let success = (data => {
				this.orgMaterial = data.data;
			})

			if (this.$store.state.isCheckLevel) {
				this.$ajax.get('api/newlevel/platform_material', { params: this.materialParam, func: { success: success } })
			} else {
				this.$ajax.get('api/cate/material', { params: this.materialParam, func: { success: success } })
			}

		},
		//获取章
		getList1() {
			this.listParam1.material_id = this.dataForm.material_id;
			let success = (data => {
				this.orgList1 = data.data;
			})

			this.$ajax.get('api/cate/cate_list', { params: this.listParam1, func: { success: success } })
		},
		//获取节
		getList2() {
			this.listParam2.material_id = this.dataForm.material_id;
			this.listParam2.pid = this.dataForm.list_1_id;
			let success = (data => {
				this.orgList2 = data.data;
			})
			this.$ajax.get('api/cate/cate_list', { params: this.listParam2, func: { success: success } })
		},

		resetOrgGrade() {
			this.dataForm.grade_id = 0;
		},
		/**
		 * 联动下拉框的方法
		 * @DateTime 2020-03-05T10:44:43+0800
		 * @param    {[type]}                 newVal [选中的id]
		 * @param    {[type]}                 type   [类型]
		 * @return   {[type]}                        [description]
		 */
		relateChange(newVal, type) {
			// console.info(obj,dd)
			switch (type) {
				case 'study_section':
					this.dataForm.grade_id = undefined;
					this.dataForm.subject_id = undefined;
					this.dataForm.version_id = undefined;
					this.dataForm.material_id = undefined;
					this.dataForm.list_1_id = undefined;
					this.dataForm.list_2_id = undefined;

					this.orgLevel3 = [];
					this.orgSubject = [];
					this.orgVersion = [];
					this.orgMaterial = [];
					this.orgList1 = [];
					this.orgList2 = [];

					this.orgLevelParam.pid = newVal;
					this.getOrgLevel3();
					break;
				case 'grade':
					this.dataForm.subject_id = undefined;
					this.dataForm.version_id = undefined;
					this.dataForm.material_id = undefined;
					this.dataForm.list_1_id = undefined;
					this.dataForm.list_2_id = undefined;

					this.orgSubject = [];
					this.orgVersion = [];
					this.orgMaterial = [];
					this.orgList1 = [];
					this.orgList2 = [];


					this.subjectParam.org_id = newVal;
					this.getSubject();

					this.versionParam.org_id = newVal;
					this.materialParam.org_id = newVal;
					break;
				case 'subject':
					this.dataForm.version_id = undefined;
					this.dataForm.material_id = undefined;
					this.dataForm.list_1_id = undefined;
					this.dataForm.list_2_id = undefined;

					this.orgVersion = [];
					this.orgMaterial = [];
					this.orgList1 = [];
					this.orgList2 = [];

					this.versionParam.sub_id = newVal;
					this.getVersion();

					this.materialParam.sub_id = newVal;
					break;
				case 'version':
					this.dataForm.material_id = undefined;
					this.dataForm.list_1_id = undefined;
					this.dataForm.list_2_id = undefined;

					this.orgMaterial = [];
					this.orgList1 = [];
					this.orgList2 = [];

					this.materialParam.ver_id = newVal;
					this.getMaterial();
					break;
				case 'material':
					this.dataForm.list_1_id = undefined;
					this.dataForm.list_2_id = undefined;

					this.orgList1 = [];
					this.orgList2 = [];

					this.listParam1.material_id = newVal;
					this.listParam2.material_id = newVal;
					this.getList1();
					break;
				case 'list_1':
					this.dataForm.list_2_id = undefined;
					this.orgList2 = [];

					this.listParam2.pid = newVal;
					this.getList2();
					break;
				default:
					break;

			}
		}

	},
	mounted() {
		// 获取uploader对象  
		this.$nextTick(() => {
			window.Uploader = this.$refs.uploader.uploader
		})
	}
}
</script>